package com.jg.visitor.filter;

import com.jg.visitor.GlobalConst;
import com.jg.visitor.common.bean.LicenseBean;
import com.jg.visitor.config.autoconfiguration.caffeinecache.service.CacheService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;


@WebFilter(filterName="LicenseFilter",urlPatterns="/*")
@Order(3)
@Slf4j
public class LicenseFilter implements Filter {
    @Resource
    private CacheService cacheService;

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("init");
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LicenseBean licenseBean = cacheService.getCache(GlobalConst.LICENSE_CONFIG, GlobalConst.LICENSE_CONFIG_KEY, LicenseBean.class);
        if(licenseBean != null){
            Thread.sleep(licenseBean.getSleepTime() * 1000);
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        log.info("destroy");
    }

}
